package com.test.controller.user;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.test.entity.po.TestAdminPO;
import com.test.entity.vo.TestAdminVO;
import com.test.entity.vo.TestTreenodeVO;
import com.test.service.TestAdminService;
import com.test.service.TestMenuService;
import com.test.util.BaseErrorConstant;
import com.test.util.Encrypt;
import com.test.util.InvokeResult;
import com.test.util.InvokeStateEnum;
import com.test.util.StringUtil;

/**
 * 
 * @ClassName: UserController 
 * @Description: 用户登录管理类 
 * @author weiqi 
 * @date 2017年3月20日 上午12:07:43
 */
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private TestAdminService adminService;
	
	@Autowired
	private TestMenuService treenodeService;
	
	@RequestMapping(value="/validateLogin",method=RequestMethod.POST)
	public @ResponseBody InvokeResult validateLogin(String name, String password, String token, HttpServletRequest request) throws Exception{
		InvokeResult result = null;
		//验证token
		String session_token = (String)request.getSession().getAttribute("token");
		//如果表单提交的token为空或者session中存储的token为空或者用户提交的token与session中存储的token不一样,则用户重复提交了表单
		if(token==null || session_token==null || !token.equals(session_token)){
			result = new InvokeResult(InvokeStateEnum.ERROR.getCode(), BaseErrorConstant.TOKEN_ERROR);
		}else{
			if(StringUtil.isNotEmpty(name) && StringUtil.isNotEmpty(password)){
				HttpSession session = request.getSession();
				TestAdminPO adminPO = new TestAdminPO();
				adminPO.setUser(name);
				adminPO.setPassword(Encrypt.EncodMd5(password));
				TestAdminVO adminVO = adminService.selectAdmin(adminPO);
				if (null != adminVO) {
					session.setAttribute("session_user" , adminVO);
					List<TestTreenodeVO> list = treenodeService.selectTestTreenodeByUserId(adminVO.getId());
					session.setAttribute("session_menu" , list);
					result = new InvokeResult(InvokeStateEnum.SUCCESS.getCode(), null);
				} else {
					result = new InvokeResult(InvokeStateEnum.ERROR.getCode(), BaseErrorConstant.RESULT_NULL_ERROR);
				}
			}else {
				result = new InvokeResult(InvokeStateEnum.ERROR.getCode(), BaseErrorConstant.PARAM_ERROR);
			}
		}
		return result;
	}
}
